using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(Collider2D))]
public class Interactable:MonoBehaviour {

	virtual protected void Start() {
		spriteRenderer=GetComponent<SpriteRenderer>();
		collider=GetComponent<Collider2D>();
	}
	virtual protected void Update() {
		if(this==selected) spriteRenderer.material=materialSelected;
		else spriteRenderer.material=materialNormal;
	}
	virtual protected void OnEnable() { instances.Add(this); }
	virtual protected void OnDisable() { instances.Remove(this); }

	virtual protected void HandleInteract() { }

	virtual protected void UpdateSelected() {

		if(!collider) return;

		Bounds bound1 = collider.bounds;
		bound1.center=new Vector3(bound1.center.x,bound1.center.y,0);
		Bounds bound2 = Player.instance.collider.bounds;
		bound2.center=new Vector3(bound2.center.x,bound2.center.y,0);


		if(bound1.Intersects(bound2)) {
			
			float currentDistance = Vector2.Distance(transform.position,Player.instance.transform.position);
			if(currentDistance<closestDistance) {
				closestDistance=currentDistance;
				selected=this;
			}
		}

	}

	//引用
	protected new Collider2D collider;
	protected SpriteRenderer spriteRenderer;

	[SerializeField] protected Material materialSelected;
	[SerializeField] protected Material materialNormal;

	//static
	protected static float closestDistance;
	public static Interactable selected { get; protected set; }

	static HashSet<Interactable> instances = new HashSet<Interactable>();
	[RuntimeInitializeOnLoadMethod]
	static void SubscribeEventsStatic() {
		StaticEventManager.UpdateStatic+=UpdateStaticEventHandler;
	}
	static void UpdateStaticEventHandler(object sender) {
		closestDistance=float.MaxValue;
		selected=null;
		foreach(Interactable i in instances) i.UpdateSelected();
	}

	public static void Interact() {
		if(selected) selected.HandleInteract();
	}
}